import React from 'react';
import * as am4core from '@amcharts/amcharts4/core'
import * as am4charts from '@amcharts/amcharts4/charts'
import * as am4plugins_overlapBuster from "@amcharts/amcharts4/plugins/overlapBuster";

// import am4themes_animated from '@amcharts/amcharts4/themes/animated'
import Logo from '../../logo.svg'

export default class LineAmcharts extends React.Component {
  getChartData = (categoryAxis) => {
    ///// DATA
    let chartData = [];

    let data =
    {
      "Provider 1": {
        "item 1": 10,
        "item 2": 35,
        "item 3": 5,
        "item 4": 20,
        "quantity": 430
      },
      "Provider 2": {
        "item 1": 15,
        "item 3": 21,
        "quantity": 210
      },
      "Provider 3": {
        "item 2": 25,
        "item 3": 11,
        "item 4": 17,
        "quantity": 265
      },
      "Provider 4": {
        "item 3": 12,
        "item 4": 15,
        "quantity": 98
      }
    }

    // process data ant prepare it for the chart
    for (var providerName in data) {
      let providerData = data[providerName];

      // add data of one provider to temp array
      let tempArray = [];
      let count = 0;
      // add items
      for (var itemName in providerData) {
        if (itemName != "quantity") {
          count++;
          // we generate unique category for each column (providerName + "_" + itemName) and store realName
          tempArray.push({ category: providerName + "_" + itemName, realName: itemName, value: providerData[itemName], provider: providerName })
        }
      }
      // sort temp array
      tempArray.sort(function (a, b) {
        if (a.value > b.value) {
          return 1;
        }
        else if (a.value < b.value) {
          return -1
        }
        else {
          return 0;
        }
      })

      // add quantity and count to middle data item (line series uses it)
      let lineSeriesDataIndex = Math.floor(count / 2);
      tempArray[lineSeriesDataIndex].quantity = providerData.quantity;
      tempArray[lineSeriesDataIndex].count = count;
      // push to the final data
      am4core.array.each(tempArray, function (item) {
        chartData.push(item);
      })

      // create range (the additional label at the bottom)
      let range = categoryAxis.axisRanges.create();
      range.category = tempArray[0].category;
      range.endCategory = tempArray[tempArray.length - 1].category;
      range.label.text = tempArray[0].provider;
      range.label.dy = 30;
      range.label.truncate = true;
      range.label.fontWeight = "bold";
      range.label.tooltipText = tempArray[0].provider;

      range.label.adapter.add("maxWidth", function (maxWidth, target) {
        let range = target.dataItem;
        let startPosition = categoryAxis.categoryToPosition(range.category, 0);
        let endPosition = categoryAxis.categoryToPosition(range.endCategory, 1);
        let startX = categoryAxis.positionToCoordinate(startPosition);
        let endX = categoryAxis.positionToCoordinate(endPosition);
        return endX - startX;
      })
    }
    return chartData
  }
  createXAxis = () => {
    let chart = this.chart
    let categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
    categoryAxis.dataFields.category = "category";
    categoryAxis.renderer.minGridDistance = 60;
    categoryAxis.renderer.grid.template.location = 0;
    categoryAxis.dataItems.template.text = "{realName}";
    categoryAxis.adapter.add("tooltipText", function (tooltipText, target) {
      return categoryAxis.tooltipDataItem.dataContext.realName;
    })
    // let rangeTemplate = categoryAxis.axisRanges.template;
    // rangeTemplate.tick.disabled = false;
    // rangeTemplate.tick.location = 0;
    // rangeTemplate.tick.strokeOpacity = 1;
    // rangeTemplate.tick.length = 60;
    // rangeTemplate.grid.strokeOpacity = 0.5;
    // rangeTemplate.label.tooltip = new am4core.Tooltip();
    // rangeTemplate.label.tooltip.dy = -10;
    // rangeTemplate.label.cloneTooltip = false;
    return categoryAxis
  }
  createYAxis = () => {
    let chart = this.chart
    let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
    valueAxis.tooltip.disabled = true;
    valueAxis.min = 0;
    return valueAxis
  }
  createSecondY = (valueAxis) => {
    let chart = this.chart
    // second value axis for quantity
    let valueAxis2 = chart.yAxes.push(new am4charts.ValueAxis());
    valueAxis2.renderer.opposite = true;
    valueAxis2.syncWithAxis = valueAxis;
    valueAxis2.tooltip.disabled = true;
    return valueAxis2
  }
  createOne = () => {
    let chart = this.chart
    let colors = {};

    // single column series for all data
    let columnSeries = chart.series.push(new am4charts.ColumnSeries());
    columnSeries.columns.template.width = am4core.percent(80);
    columnSeries.tooltipText = "{provider}: {realName}, {valueY}";
    columnSeries.dataFields.categoryX = "category";
    columnSeries.dataFields.valueY = "value";

    // fill adapter, here we save color value to colors object so that each time the item has the same name, the same color is used
    columnSeries.columns.template.adapter.add("fill", function (fill, target) {
      let name = target.dataItem.dataContext.realName;
      if (!colors[name]) {
        colors[name] = chart.colors.next();
      }
      target.stroke = colors[name];
      return colors[name];
    })
    // let series = chart.series.push(new am4charts.LineSeries())
    // series.dataFields.categoryX = 'year'
    // series.name = 'cars'
    // series.dataFields.valueY = 'namerica'
    // series.tooltipHTML = "<img src='https://www.amcharts.com/lib/3/images/car.png' style='vertical-align:bottom; margin-right: 10px; width:28px; height:21px;'><span style='font-size:14px; color:#000000;'><b>{valueY.value}</b></span>";
    // series.tooltipText = "[#000]{valueY.value}[/]";
    // series.tooltip.background.fill = am4core.color("#FFF");
    // series.tooltip.getStrokeFromObject = true;
    // series.tooltip.background.strokeWidth = 3;
    // series.tooltip.getFillFromObject = false;
    // series.fillOpacity = 0.2;
    // series.strokeWidth = 0;
    // series.stacked = true;
    // series.sequencedInterpolation = true

    // let bullet = series.bullets.push(new am4charts.Bullet());
    // let image = bullet.createChild(am4core.Image);
    // image.horizontalCenter = "middle";
    // image.verticalCenter = "bottom";
    // image.dy = 0;
    // image.y = am4core.percent(100);
    // image.propertyFields.href = "series1";
    // // image.adapter.add('href', (a, b, c) => {
    // //   console.log(a, b, c)
    // //   return "series1"
    // // })
    // // image.tooltipText = series.value.tooltipText;
    // image.propertyFields.fill = "color";
    // image.filters.push(new am4core.DropShadowFilter());

    // // 添加渐变色
    // let gradient = new am4core.LinearGradient();
    // gradient.addColor('#018580')
    // gradient.addColor('white');
    // gradient.rotation += 90
    // columnSeries.fill = gradient;
    // let overlap = chart.plugins.push(new am4plugins_overlapBuster.OverlapBuster());
    // overlap.targets.push(bullet);
  }
  createTwo = () => {
    let chart = this.chart
    // quantity line series
    let lineSeries = chart.series.push(new am4charts.LineSeries());
    lineSeries.tooltipText = "{valueY}";
    lineSeries.dataFields.categoryX = "category";
    lineSeries.dataFields.valueY = "quantity";
    lineSeries.yAxis = this.Y;
    lineSeries.bullets.push(new am4charts.CircleBullet());
    lineSeries.stroke = chart.colors.getIndex(13);
    lineSeries.fill = lineSeries.stroke;
    lineSeries.strokeWidth = 2;
    lineSeries.snapTooltip = true;

    // when data validated, adjust location of data item based on count
    lineSeries.events.on("datavalidated", function () {
      lineSeries.dataItems.each(function (dataItem) {
        // if count divides by two, location is 0 (on the grid)
        if (dataItem.dataContext.count / 2 == Math.round(dataItem.dataContext.count / 2)) {
          dataItem.setLocation("categoryX", 0);
        }
        // otherwise location is 0.5 (middle)
        else {
          dataItem.setLocation("categoryX", 0.5);
        }
      })
    })
    // let series2 = chart.series.push(new am4charts.LineSeries());
    // series2.name = "Europe1";
    // series2.dataFields.categoryX = "year";
    // series2.dataFields.valueY = "motorcycles";
    // series2.tooltipHTML = "<img src='https://www.amcharts.com/lib/3/images/motorcycle.png' style='vertical-align:bottom; margin-right: 10px; width:28px; height:21px;'><span style='font-size:14px; color:#000000;'><b>{valueY.value}</b></span>";
    // series2.tooltipText = "[#000]{valueY.value}[/]";
    // series2.tooltip.background.fill = am4core.color("#FFF");
    // series2.tooltip.getFillFromObject = false;
    // series2.tooltip.getStrokeFromObject = true;
    // series2.tooltip.background.strokeWidth = 3;
    // series2.sequencedInterpolation = true;
    // series2.fillOpacity = 0.6;
    // series2.stacked = true;
    // series2.strokeWidth = 0;

    // let bullet = series2.bullets.push(new am4charts.Bullet());
    // let image = bullet.createChild(am4core.Image);
    // image.horizontalCenter = "middle";
    // image.verticalCenter = "bottom";
    // image.dy = 20;
    // image.y = am4core.percent(100);
    // image.propertyFields.href = "series2";
    // // image.tooltipText = series.value.tooltipText;
    // image.propertyFields.fill = "color";
    // image.filters.push(new am4core.DropShadowFilter());

    let gradient = new am4core.LinearGradient();
    gradient.addColor('#1564B5')
    gradient.addColor('white');
    gradient.rotation += 90
    lineSeries.fill = gradient;
    // let overlap = chart.plugins.push(new am4plugins_overlapBuster.OverlapBuster());
    // overlap.targets.push(bullet);
  }
  createThree = () => {
    let chart = this.chart
    let series3 = chart.series.push(new am4charts.LineSeries());
    series3.name = "bicycles";
    series3.dataFields.categoryX = "year";
    series3.dataFields.valueY = "africa";
    series3.tooltipHTML = "<img src='https://www.amcharts.com/lib/3/images/bicycle.png' style='vertical-align:bottom; margin-right: 10px; width:28px; height:21px;'><span style='font-size:14px; color:#000000;'><b>{valueY.value}</b></span>";
    series3.tooltipText = "[#000]{valueY.value}[/]";
    series3.tooltip.background.fill = am4core.color("#FFF");
    series3.tooltip.getFillFromObject = false;
    series3.tooltip.getStrokeFromObject = true;
    series3.tooltip.background.strokeWidth = 3;
    series3.sequencedInterpolation = true;
    series3.fillOpacity = 0.6;
    series3.defaultState.transitionDuration = 1000;
    series3.stacked = true;
    series3.strokeWidth = 0;

    let bullet = series3.bullets.push(new am4charts.Bullet());
    let image = bullet.createChild(am4core.Image);
    image.horizontalCenter = "middle";
    image.verticalCenter = "bottom";
    image.dy = 20;
    image.y = am4core.percent(100);
    image.propertyFields.href = "series3";
    // image.tooltipText = series.value.tooltipText;
    image.propertyFields.fill = "color";
    image.filters.push(new am4core.DropShadowFilter());
    let overlap = chart.plugins.push(new am4plugins_overlapBuster.OverlapBuster());
    overlap.targets.push(bullet);
  }
  createSeries = (field, name, stacked, opacity = 1) => {
    let chart = this.chart
    let series = chart.series.push(new am4charts.ColumnSeries());
    series.dataFields.valueY = field;
    series.dataFields.categoryX = "year";
    series.name = name;
    series.columns.template.tooltipText = "{name}: [bold]{valueY}[/]";
    // 控制堆叠的属性
    series.stacked = stacked;
    // 通过透明度 来控制 显示和隐藏
    series.opacity = opacity
    series.columns.template.width = am4core.percent(95);
  }
  optionChart = () => {
    let chart = this.chart
    // chart.cursor = new am4charts.XYCursor();
    // chart.cursor.xAxis = this.X;
    // chart.scrollbarX = new am4core.Scrollbar();

    // Add a legend
    chart.legend = new am4charts.Legend();
    chart.legend.position = "top";

    // // axis ranges
    let range = this.X.axisRanges.create();
    range.value = 2001
    range.endValue = 2003
    range.axisFill.fill = chart.colors.getIndex(7);
    range.axisFill.fillOpacity = 0.2;

    range.label.text = "Fines for speeding increased";
    range.label.inside = true;
    range.label.rotation = 90;
    range.label.horizontalCenter = "right";
    range.label.verticalCenter = "bottom";

    let range2 = this.X.axisRanges.create();
    range2.value = 2007
    range2.grid.stroke = chart.colors.getIndex(7);
    range2.grid.strokeOpacity = 0.6;
    range2.grid.strokeDasharray = "5,2";


    range2.label.text = "Motorcycle fee introduced";
    range2.label.inside = true;
    range2.label.rotation = 90;
    range2.label.horizontalCenter = "right";
    range2.label.verticalCenter = "bottom";
  }
  initAmchart() {
    let chart = this.chart
    chart.paddingBottom = 50;

    this.X = this.createXAxis()
    this.Y = this.createYAxis()
    this.createOne()
    // let  = this.createSecondY(this.Y)
    this.createTwo()
    chart.data = this.getChartData(this.X);

  }
  componentDidMount() {
    // Create chart instance
    // Themes begin
    // am4core.useTheme(am4themes_animated);
    // Themes end
    // / Create chart instance
    let chart = am4core.create("grouped-and-sorted-columns", am4charts.XYChart);
    this.chart = chart;
    this.initAmchart()
  }
  componentWillUnmount() {
    this.chart.dispose()
  }
  render() {
    return (
      <div id='grouped-and-sorted-columns'></div>
    )
  }
}